const bcrypt = require("bcryptjs");

const { getUserInfo } = require("../service/user.service");
const {
  USER_FORMATE_ERROR,
  UESRNAME_ALREADY_EXISTS,
  USER_REGISTER_ERROR,
  USER_DOES_NOT_EXIST,
  USER_LOGIN_ERROE,
  INVALID_PASSWORD,
  PASSWORD_ABNORMALITY,
} = require("../constant/err.type");

/**
 * 验证用户信息是否存在
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
const userValidator = async (ctx, next) => {
  try {
    const { username, password } = ctx?.request?.body;
    if (!username || !password) {
      console.error(USER_FORMATE_ERROR.msg, ctx?.request?.body);
      ctx.app.emit("error", USER_FORMATE_ERROR, ctx);
      return;
    }
  } catch (error) {
    console.error(USER_REGISTER_ERROR.msg, error);
    ctx.app.emit("error", USER_REGISTER_ERROR, ctx);
    return;
  }
  await next();
};

/**
 * 验证用户名是否存在
 * @param {*} ctx
 * @param {*} next
 * @returns
 */
const verifyUsername = async (ctx, next) => {
  try {
    const { username } = ctx?.request?.body;

    const res = await getUserInfo({ username });
    if (res) {
      console.error(UESRNAME_ALREADY_EXISTS.msg, ctx?.request?.body);
      ctx.app.emit("error", UESRNAME_ALREADY_EXISTS, ctx);
      return;
    }
  } catch (error) {
    console.error(USER_REGISTER_ERROR.msg, error);
    ctx.app.emit("error", USER_REGISTER_ERROR, ctx);
    return;
  }
  await next();
};

/**
 * 对密码进行加密
 * @param {*} ctx
 * @param {*} next
 */
const crpytPassword = async (ctx, next) => {
  try {
    const { password } = ctx?.request?.body;
    const salt = bcrypt.genSaltSync(10);
    const hash = bcrypt.hashSync(password, salt);
    ctx.request.body.password = hash;
    await next();
  } catch (error) {
    console.error(PASSWORD_ABNORMALITY.msg, error);
    ctx.app.emit("error", PASSWORD_ABNORMALITY, ctx);
    return;
  }
};

/**
 * 登录校验
 * @param {*} ctx
 * @param {*} next
 */
const verifyLogin = async (ctx, next) => {
  try {
    const { username, password } = ctx?.request?.body;

    const res = await getUserInfo({ username });
    console.log("res", res);

    if (!res) {
      console.error(USER_DOES_NOT_EXIST.msg, ctx?.request?.body);
      ctx.app.emit("error", USER_DOES_NOT_EXIST, ctx);
      return;
    }

    if (!bcrypt.compareSync(password, res.password)) {
      console.error(INVALID_PASSWORD.msg, ctx?.request?.body);
      ctx.app.emit("error", INVALID_PASSWORD, ctx);
      return;
    }
  } catch (error) {
    console.error(USER_LOGIN_ERROE.msg, error);
    ctx.app.emit("error", USER_LOGIN_ERROE, ctx);
    return;
  }

  await next();
};

module.exports = {
  userValidator,
  verifyUsername,
  crpytPassword,
  verifyLogin,
};
